<template>
	<view class="rf-product-list">
		<view class="rf-product-list-container">
			<block v-for="(item, index) in list" :key="index">
				<!--商品列表-->
				<view
					v-if="(index + 1) % 2 !== 0 || isList"
					class="rf-product-item"
					@tap.stop="navTo(`/pages/product/product?id=${item.id}`)"
					:class="[isList ? 'rf-product-flex-list' : '']"
					hover-class="hover"
					:hover-start-time="150"
				>
					<view class="rf-left-section">
						<view class="rf-product-image-wrapper">
							<image :src="item.picture" mode="aspectFill" class="rf-product-img"></image>
						</view>
						<view class="rf-button-row">
							<text class="rf-pro-btn" @tap.stop="copyProductInfo(item)">复制</text>
							<button class="rf-pro-btn" @tap.stop="downloadDocument(item.document)">说明书</button>
						</view>
					</view>
					<view class="rf-pro-content">
						<view class="rf-pro-title-row">
							<text class="rf-pro-tit">{{ item.name }}</text>
						</view>
						<view class="rf-pro-info-row">
							<view class="rf-pro-info-intro-row">

								<rich-text v-if="item.intro_h5" :nodes="item.intro_h5"></rich-text>
								<rich-text v-else :nodes="item.intro"></rich-text>
							</view>
						</view>
					</view>
				</view>
				<!--商品列表-->
			</block>
		</view>

		<!-- 规格-模态层弹窗 -->
		<view
			class="popup spec show"
			v-if="specClass === 'show'"
			@touchmove.stop.prevent="stopPrevent"
			@tap="hideSpec"
		>
			<!-- 遮罩层 -->
			<view class="mask" @tap="hideSpec"></view>
			<view class="layer" :style="{bottom: bottom ? `${bottom}upx` : 0}" @tap.stop="stopPrevent">
				<rf-attr-content
					:product="productDetail"
					@toggle="toggleSpec"
					:showBuyBtn="true"
				></rf-attr-content>
			</view>
		</view>
		<uni-popup v-if="copySuccessDialog" type="center" :mask-click="false">
			<view style="padding: 32rpx 48rpx; background: #fff; border-radius: 12rpx; text-align: center;">
				<text style="font-size: 32rpx; color: #222;">复制成功</text>
				<view style="margin-top: 32rpx;">
					<button style="background: #e53935; color: #fff; border-radius: 8rpx; padding: 12rpx 48rpx; font-size: 28rpx;" @tap="copySuccessDialog = false">确定</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>
<script>
/**
 * @des 商品列表
 *
 * @author stav stavyan@qq.com
 * @date 2020-05-15 10:49
 */
import { productDetail, cartItemCount, cartItemCreate } from '@/api/product';
import rfAttrContent from '@/components/rf-attr-content';
import $mAssetsPath from '@/config/assets.config';
import { mapMutations } from 'vuex';
export default {
	name: 'rfProductList',
	props: {
		list: {
			type: Array,
			default() {
				return [];
			}
		},
		// 是否以列表展示 | 列表或大图
		isList: {
			type: Boolean,
			default: true
		},
		// 是否以列表展示 | 列表或大图
		bottom: {
			type: Number,
			default: 0
		}
	},
	components: {
		rfAttrContent
	},
	data() {
		return {
			specClass: 'none',
      moneySymbol: this.moneySymbol,
			productDetail: {},
			copySuccessDialog: false,
		};
	},
	filters: {
		filterTotalSales(val) {
			if (val > 10000) {
				val = `${(val / 10000).toFixed(2)}w`;
			}
			return val;
		},
		filterTagName(val) {
			if (val.commissionRate) {
				// 分销商品
				return $mAssetsPath.distribution;
			} else if (val.is_virtual === '1') {
				// 虚拟产品
				return $mAssetsPath.virtual;
			} else if (val.shipping_type === '1') {
				// 包邮产品
				return $mAssetsPath.pinkage;
			}
		}
	},
	methods: {
    ...mapMutations(['setCartNum']),
		// 跳转详情
		navTo(route) {
			this.$mRouter.push({ route });
		},
		// 复制商品信息到剪切板
		copyProductInfo(item) {
			// 处理HTML标签：将<br>替换为换行符，去掉其他HTML标签
			const cleanIntro = this.cleanHtmlTags(item.intro_h5 || item.intro || '');

			// const info = `名称：${item.name}\n简介：${item.sketch}\n型号：${item.model || item.sn || item.code || '-'}\n价格：￥${item.price}\n范围：${item.range || '1-1000pg/mL'}\n灵敏度：${item.sensitivity || '35pg/mL'}`;
			const info = `产品名称：${item.name}\n货号：${item.skustr}\n${cleanIntro}\n产品详情地址：https://www.enkilife.cn/h5/#/pages/product/product?id=${item.id}\n产品说明书地址：${item.document || '暂无'}`;


			// #ifdef H5
			if (navigator && navigator.clipboard && window.isSecureContext) {
				navigator.clipboard.writeText(info).then(() => {
					this.copySuccessDialog = true;
							uni.showToast({ title: '已复制', icon: 'none' });
				}).catch(() => {
					this._fallbackCopyTextToClipboard(info);
				});
			} else {
				this._fallbackCopyTextToClipboard(info);
			}
			// #endif

			// #ifdef MP-WEIXIN || APP-PLUS || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO
			uni.setClipboardData({
				data: info,
				success: () => {
					this.copySuccessDialog = true;
							uni.showToast({ title: '已复制', icon: 'none' });
				},
				fail: () => {
					uni.showToast({ title: '复制失败', icon: 'none' });
				}
			});
			// #endif
		},
		_fallbackCopyTextToClipboard(text) {
			const textarea = document.createElement('textarea');
			textarea.value = text;
			textarea.setAttribute('readonly', '');
			textarea.style.position = 'absolute';
			textarea.style.left = '-9999px';
			document.body.appendChild(textarea);
			textarea.select();
			let success = false;
			try {
				success = document.execCommand('copy');
			} catch (err) {
				success = false;
			}
			document.body.removeChild(textarea);
			if (success) {
				this.copySuccessDialog = true;
					uni.showToast({ title: '已复制', icon: 'none' });
			} else {
				uni.showToast({ title: '复制失败', icon: 'none' });
			}
		},
		// 下载说明书
		downloadDocument(url) {
			if (!url) {
				uni.showToast({ title: '无说明书', icon: 'none' });
				return;
			}

			// 检查URL是否合法
			try {
				new URL(url);
			} catch (e) {
				uni.showToast({ title: 'URL不合法', icon: 'none' });
				return;
			}

			// 解码URL
			try {
				url = decodeURIComponent(url);
			} catch (e) {
				console.error('URL解码失败:', e);
			}

			console.log(url);
			// #ifdef H5
			// 在新窗口中打开文件
			window.open(url, '_blank');
			uni.showToast({ title: '正在打开文件', icon: 'none' });
			return;
			// #endif

			// 非H5环境
			uni.showLoading({ title: '下载中...' });
			uni.downloadFile({
				url,
				success: (res) => {
					uni.hideLoading();
					if (res.statusCode === 200) {
						// 保存文件到本地
						uni.saveFile({
							tempFilePath: res.tempFilePath,
							success: () => {
								uni.showToast({
									title: '下载成功',
									icon: 'success',
									duration: 2000
								});
							},
							fail: () => {
								uni.showToast({
									title: '保存失败',
									icon: 'none',
									duration: 2000
								});
							}
						});
					} else {
						uni.showToast({
							title: '下载失败，请稍后重试',
							icon: 'none'
						});
					}
				},
				fail: () => {
					uni.hideLoading();
					uni.showToast({
						title: '下载失败，请检查网络后重试',
						icon: 'none',
						duration: 2000
					});
				}
			});
		},
		// 获取产品详情
		async getProductDetail(row) {
			await this.$http
				.get(`${productDetail}`, {
					id: row.id
				})
				.then(async r => {
					this.productDetail = await r.data;
					this.productDetail.sku_name = row.sku_name;
					this.specClass = 'show';
				});
		},
		// 规格弹窗开关
		toggleSpec(row) {
			if (parseInt(row.status, 10) === 0) return;
			if (this.specClass === 'show') {
				this.specClass = 'hide';
				if (row.stock === 0) {
					this.$mHelper.toast('库存不足');
					return;
				}
				if (row.type.toString() === '1') {
					// 加入购物车
					this.handleCartItemCreate(row.skuId, row.cartCount);
				} else if (row.type.toString() === '2') {
					// 立即购买
					const list = {};
					const data = {};
					data.sku_id = row.skuId;
					data.num = row.cartCount;
					if (
						this.productDetail.point_exchange_type.toString() === '2' ||
						this.productDetail.point_exchange_type.toString() === '4' ||
						(this.productDetail.point_exchange_type.toString() === '3' &&
							this.isPointExchange)
					) {
						list.type = 'point_exchange';
					} else {
						list.type = 'buy_now';
					}
					list.data = JSON.stringify(data);
					this.navTo(`/pages/order/create/order?data=${JSON.stringify(list)}`);
				}
				setTimeout(() => {
					this.specClass = 'none';
				}, 250);
			} else if (this.specClass === 'none') {
				this.getProductDetail(row);
			}
		},
		stopPrevent() {},
		hideSpec() {
			this.specClass = 'hide';
			setTimeout(() => {
				this.specClass = 'none';
			}, 250);
		},
		// 添加商品至购物车
		async handleCartItemCreate(skuId, cartCount) {
			await this.$http
				.post(`${cartItemCreate}`, {
					sku_id: skuId,
					num: cartCount
				})
				.then(async () => {
					await this.$http.get(`${cartItemCount}`).then(async r => {
						this.setCartNum(r.data);
					});
					this.$mHelper.toast('添加购物车成功');
				});
		},
		// 清理HTML标签：将<br>替换为换行符，去掉其他HTML标签
		cleanHtmlTags(htmlString) {
			if (!htmlString) return '';

			// 将<br>、<br/>、<br />等标签替换为换行符
			let cleanText = htmlString.replace(/<br\s*\/?>/gi, '\n');

			// 去掉所有其他HTML标签
			cleanText = cleanText.replace(/<[^>]*>/g, '');

			// 解码HTML实体
			cleanText = cleanText.replace(/&nbsp;/g, ' ');
			cleanText = cleanText.replace(/&lt;/g, '<');
			cleanText = cleanText.replace(/&gt;/g, '>');
			cleanText = cleanText.replace(/&amp;/g, '&');
			cleanText = cleanText.replace(/&quot;/g, '"');
			cleanText = cleanText.replace(/&#39;/g, "'");

			// 清理多余的空白字符，但保留换行符
			cleanText = cleanText.replace(/[ \t]+/g, ' ').trim();

			return cleanText;
		}
	}
};
</script>
<style lang="scss" scoped>


// 通用商品列表
.rf-product-list {
	background-color: $page-color-base;
	padding: 0 $spacing-sm;
	width: 100%;
	box-sizing: border-box;

	.rf-product-list-container {
		width: 100%;
		margin-right: 0;
	}

	.rf-product-item {
		margin-bottom: 10upx;
		box-sizing: border-box;
		background: $color-white;
		border-radius: 12upx;
		overflow: hidden;
		transition: all 0.15s ease-in-out;
		display: flex;
		flex-direction: row;
		align-items: flex-start;
		padding: 20rpx;
	}

	.rf-left-section {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-right: 20rpx;
		flex-shrink: 0;
	}

	.rf-button-row {
		display: flex;
		flex-direction: row;
		gap: 10rpx;
		margin-top: 15rpx;
		width: 260rpx;
		justify-content: center;
		align-items: center;
	}

	// 列表模式特殊样式
	.rf-product-flex-list {
		.rf-left-section {
			margin-right: 15rpx;
		}

		.rf-button-row {
			margin-top: 10rpx;
		}
	}

	.rf-product-image-wrapper {
		width: 260rpx;
		height: 220rpx;
		flex-shrink: 0;
		border-radius: 6upx;
		overflow: hidden;
		position: relative;

		.rf-product-img {
			width: 100%;
			height: 100% !important;
			border-radius: 12upx;
			display: block;
			object-fit: cover;
		}
	}

	.rf-pro-content {
		flex: 1;
		min-width: 0;
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
		box-sizing: border-box;

		.rf-pro-title-row {
			width: 100%;
			// margin-bottom: 10rpx;

			.rf-pro-tit {
				width: 100%;
				min-height: 60rpx;
				color: #2e2e2e;
				font-weight: bold;
				font-size: 26rpx;
				word-break: break-all;
				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 2;
			}
		}

		.rf-pro-info-row {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: flex-start;
			box-sizing: border-box;
			width: 100%;
			gap: 20rpx;

			.rf-pro-info-intro-row {
				flex: 1;
				min-width: 0;
				font-size: 24rpx;
				line-height: 1.5;
				color: #666;
				overflow: hidden;

				:deep(p) {
					margin: 5rpx 0;
					word-break: break-all;
				}
				:deep(img) {
					max-width: 100%;
					height: auto;
				}
			}

			.rf-pro-info-option-row {
				width: 80rpx;
				flex-shrink: 0;
				display: flex;
				flex-direction: column;
				gap: 10rpx;


			}
		}
	}


	.rf-pro-option-row {
		flex:1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		box-sizing: border-box;
		font-size: 24upx;
		align-items: center;
	}


}

	.rf-pro-btn {
					width: 120rpx;
					height: 50rpx;
					min-height: 50rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					background: #e53935;
					color: #fff;
					border: none;
					border-radius: 8rpx;
					font-size: 24rpx;
					font-weight: 500;
					line-height: 1;
					box-sizing: border-box;
					padding: 0;
					white-space: nowrap;

					&:hover {
						background: #d32f2f;
					}
				}


</style>
